#include <setjmp.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

//buffer for setjmp()/longjmp()
//stores registers
jmp_buf env;

//time
long t;

//some global counters
int i, j;

//signal handler for signal "SIGALRM"
//parameter is not used
void alarm_handler(int param)
{
    //get current time and calculate the time passed
    long t1 = time(NULL) - t;

    //print time passed and values of i and j
    printf("%d second%s passed: i=%d. j=%d\n", t1, (t1 == 1) ? "" :"s", 
	   i, j);
    
    //after eight seconds, give up and go back to main with longjmp()
    if(t1 >= 8)
    {
	printf("Giving up.\n");
	longjmp(env, 1);
    }

    //else:
    //raise another alarm and catch it
    alarm(1);
    signal(SIGALRM, alarm_handler);
}

int main(int argc, char **argv)
{
    //register alarm_handler
    signal(SIGALRM, alarm_handler);
    
    //save environment 
    if(setjmp(env) != 0)
    {
	//if returned by longjmp(), end program
	printf("End.\n");
	exit(1);
    }

    //raise alarm 
    alarm(1);

    //get current time
    t = time(NULL);

    //count two variables
    for(i = 0; i < 10000; i++)
	for(j=0; j < 1000000; j++)
	    ; 
}
  

